package com.easemob.chatuidemo.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.os.Environment;

import com.easemob.chatuidemo.domain.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class FileIOUtils {
    
    private static String sdState = Environment.getExternalStorageState();
    private static String path = Environment.getExternalStorageDirectory().toString();
    
    public static void setGroupMembers(Map<String, User> groupMembers, String filename){
        String groupinfo = new Gson().toJson(groupMembers);
        File file;
        File membersUri;
        if (sdState.equals(Environment.MEDIA_MOUNTED)) {
            file = new File(path + "/flyint/groupmembers/");
            if (!file.exists()){
                file.mkdirs();
            }
            membersUri = new File(file, filename);
            try {
                if(!membersUri.exists()){
                    membersUri.createNewFile();
                } 
            }catch (IOException e) {
                e.printStackTrace();
            }
            try {
                FileOutputStream fos = new FileOutputStream(membersUri);
                fos.write(groupinfo.getBytes());
                fos.close();
                System.out.println("写入成功：");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    public static Map<String, User> getGroupMembers(String filename){
        Map<String, User> groupMenbers = new HashMap<String, User>();
        File membersUri;
        if(sdState.equals(Environment.MEDIA_MOUNTED)){
            membersUri = new File(path + "/flyint/groupmembers", filename);
            try{
//                FileInputStream is = new FileInputStream(membersUri);  
//                byte[] b = new byte[1024];  
//                is.read(b);  
//                String result = new String(b);  
//                System.out.println("读取成功："+result);
                BufferedReader br = new BufferedReader(new FileReader(membersUri));  
                String readline = "";  
                StringBuffer sb = new StringBuffer();  
                while ((readline = br.readLine()) != null) {  
                    System.out.println("readline:" + readline);
                    sb.append(readline);  
                }  
                br.close();  
                System.out.println("读取成功：" + sb.toString());

                groupMenbers = new Gson().fromJson(sb.toString(),  
                        new TypeToken<Map<String, User>>() {  
                        }.getType());
            }catch (Exception e){
                System.out.println("读取群成员信息失败" + e.getMessage());
                e.printStackTrace();
            }
            
        }
        return groupMenbers;
        
    }

}
